<template>
  <div ref="warp" class="contentWarpBox">
    <div class="searchInfo">
      <div class="left">
        <el-input v-model="searchInfo.keyPrefix" style="width:120px;" placeholder="文件名" />
        <el-button type="primary" @click="searchInfoMation">搜 索</el-button>
      </div>
      <el-button class="right" type="primary" @click="openUpload">上传文件</el-button>
    </div>
    <el-table ref="table" :data="tableData" border stripe :height="this.$getTableHeight">
      <el-table-column prop="key" label="文件名">
        <template slot-scope="scope">
          <span
            class="blue"
            @click="changeActive(scope.row.key);changeRightInfo(scope.row)"
          >{{ scope.row.key ? scope.row.key : '&nbsp;' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件大小">
        <template slot-scope="scope">
          <span v-if="scope.row.key">{{ getSize(scope.row.size) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="lastModified" label="更新时间" />
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.key" class="_primary" @click="downloadFile(scope.row)">下载</span>
          <span v-if="scope.row.key" class="_delete" @click="deleteRow(scope.row)">删除</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination clearfix">
      <el-pagination v-show="false" class="right" small layout="prev, pager, next" :total="11" />
      <div class="right">
        <el-button type="primary" :disabled="currentPage==0" @click="prevpage">上一页</el-button>
        <el-button
          type="primary"
          :disabled="currentLength!=20 &&currentPage!=0"
          @click="nextPage"
        >下一页</el-button>
      </div>
    </div>
    <div
      style="width:800px;"
      :class="active ? 'closeRightBox trans':'openRightBox trans'"
      @click.stop
    >
      <detail
        v-if="active"
        :id="jumpId"
        :right-info="rightInfo"
        :page-height="pageHeight"
        :update-right="updateRight"
        @clearJumpId="clearJumpId"
        @editor="openDialog"
      />
    </div>
    <div v-if="dialogVisible">
      <el-dialog
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        title="上传文件"
        :visible.sync="dialogVisible"
        width="450px"
        :before-close="handleClose1"
      >
        <div class="upload-demo">
          <div tabindex="0" class="el-upload el-upload--text">
            <el-button type="primary" @click="showSelectVideo">选择文件</el-button>
            <el-button type="success" :disabled="cancle" @click="authUpload">上传到服务器</el-button>
            <input
              id="fileId"
              ref="emptyInput"
              type="file"
              name="file"
              class="el-upload__input"
              @change="changeSelectFile"
            />
          </div>
          <ul class="el-upload-list el-upload-list--text">
            <li v-if="file.fileName" tabindex="0" class="el-upload-list__item is-success">
              <a class="el-upload-list__item-name">
                <i class="el-icon-document" />
                {{ file.fileName }}
              </a>
              <div
                role="progressbar"
                aria-valuenow="1"
                aria-valuemin="0"
                aria-valuemax="100"
                class="el-progress el-progress--line"
              >
                <div class="el-progress-bar">
                  <div class="el-progress-bar__outer" style="height: 2px;">
                    <div class="el-progress-bar__inner" :style="{width:authProgress + '%'}" />
                  </div>
                </div>
                <div class="el-progress__text" style="font-size: 12.8px;">{{ authProgress }}%</div>
              </div>
            </li>
          </ul>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose1">取 消</el-button>
          <el-button type="primary" @click="submitFile">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import OSS from "ali-oss";
const client = new OSS({
  region: "oss-cn-shanghai",
  accessKeyId: "LTAIxZYjNPM6pgO3",
  accessKeySecret: "11iG8LcwySD1Ryw8aT1PVrQitMNYUl",
  bucket: "syg-photo"
});
import detail from "~/components/resource/detail";
import { changeTableHeight, _searchInfo, _changeTable } from "~/utils/util";
export default {
  components: {
    detail
  },
  data() {
    return {
      globalUrl: "",
      pageHeight: "",
      dialogVisible1: false,
      updateRight: false,
      active: false,
      jumpId: "",
      authProgress: "",
      objectInfoMation: {},
      tableData: [],
      rightInfo: {},
      searchInfo: {
        delimiter: "",
        keyPrefix: "",
        maxKeys: 20,
        nextMarker: ""
      },
      dialogVisible: false,
      cancle: true,
      cacheArray: [],
      currentPage: 0,
      currentLength: 0,
      file: {
        fileName: ""
      },
      filesTypeArr: []
    };
  },
  mounted() {
    this.getInit();
  },
  methods: {
    getInit() {
      this.$post({
        url: "/manage/alioss/getListObjects",
        data: this.searchInfo
      }).then(res => {
        this.objectInfoMation = res;
        this.tableData = res.objectSummaries;
        changeTableHeight(this);
      });
    },
    async downloadFile(res) {
      let type = "";
      await this.$post({
        url: "/manage/alioss/getObjectInfo",
        data: {
          id: res.key
        }
      }).then(res => {
        type = res["Content-Type"].split("/")[1];
      });
      if (res.key.includes("-")) {
        if (res.key.includes(".")) {
          const arr = res.key.split("-");
          arr.forEach(v => {
            if (v.includes(".")) {
              type = v.slice(v.lastIndexOf("."));
            }
          });
        }
      } else {
        type = `.${type}`;
      }
      const result = client.signatureUrl(`${res.key}`, {
        response: {
          "content-disposition": `attachment; filename=${res.key}${type}`
        }
      });
      this.download(result, res);
    },
    download(data, downloadObj) {
      if (!data) {
        return;
      }
      const link = document.createElement("a");
      link.style.display = "none";
      link.href = data;
      link.setAttribute("download", `${downloadObj.key}`);
      document.body.appendChild(link);
      link.click();
    },
    submitFile() {
      if (this.authProgress != 100) {
        return false;
      }
      this.$message({
        type: "success",
        message: "操作成功"
      });
      this.getInit();
      this.dialogVisible = false;
      this.globalUrl = false;
    },
    changeSelectFile(res) {
      this.authProgress = 0;
      this.fileInfoMation = res.target.files[0];
      this.$set(this.file, "fileName", this.fileInfoMation.name);
      this.cancle = false;
    },
    authUpload() {
      this.cancle = true;
      const that = this;
      const arr = this.fileInfoMation.name.split(".");
      const extName = arr[arr.length - 1];
      const sourceFileName =
        (this.fileInfoMation.type.includes("image")
          ? "photo-"
          : this.fileInfoMation.type.includes("video")
          ? "video-"
          : "file-") +
        this.fileInfoMation.name +
        "-" +
        Date.parse(new Date());
      client
        .multipartUpload(sourceFileName, this.fileInfoMation, {
          progress: function(p, cpt) {
            that.authProgress = (Number(p) * 100).toFixed(2);
          }
        })
        .then(res => {
          let uploadUrl = res.res.requestUrls[0].includes("?uploadId=")
            ? decodeURI(res.res.requestUrls[0].split("?")[0])
            : decodeURI(res.res.requestUrls[0]);
          this.globalUrl = uploadUrl;
          const newImageInfo = {
            dataId: that.dataid,
            dataType: "资源管理上传",
            extName: "." + extName,
            fileName: sourceFileName,
            fileType: 1,
            fileUrl: uploadUrl,
            ident: 1,
            size: (this.fileInfoMation.size / 1024).toFixed(2),
            sort: 0,
            sourceFileName: this.fileInfoMation.name,
            typeCode: "COMPANY_FILE_FILE"
          };
          that.file = JSON.parse(JSON.stringify(newImageInfo));
          that.$notify({
            title: `上传成功`,
            dangerouslyUseHTMLString: true,
            message: uploadUrl,
            type: "success",
            duration: 0,
            offset: 100
          });
        });
    },
    showSelectVideo() {
      this.$refs["emptyInput"].value = "";
      document.getElementById("fileId").click();
    },
    openUpload() {
      this.dialogVisible = true;
    },
    prevpage() {
      this.currentPage -= 1;
      this.tableData = this.cacheArray.splice(this.cacheArray.length - 20);
    },
    nextPage() {
      this.searchInfo.nextMarker = this.tableData[
        this.tableData.length - 1
      ].key;
      this.cacheArray = [...this.cacheArray, ...this.tableData.slice(0)];
      this.$post({
        url: "/manage/alioss/getListObjects",
        data: this.searchInfo
      }).then(res => {
        this.currentPage += 1;
        this.currentLength = res.objectSummaries.length;
        this.tableData = res.objectSummaries;
      });
    },
    deleteRow(row) {
      this.$post({
        url: "/manage/alioss/deleteObject",
        data: {
          ids: [`${row.key}`]
        }
      }).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        });
        this.getInit();
      });
    },
    searchInfoMation(res) {
      this.searchInfo.nextMarker = "";
      this.copySearchInfo = JSON.parse(JSON.stringify(this.searchInfo));
      const result = _searchInfo(res, "", this.copySearchInfo);
      this.changeTableData(result);
    },
    changeTableData(res) {
      const that = this;
      _changeTable("/manage/alioss/getListObjects", res, that);
    },
    changeRightInfo(res) {
      this.rightInfo = res;
    },
    handleClose1() {
      this.dialogVisible = false;
    },
    handleClose() {
      this.dialogVisible1 = false;
      this.updateRight = !this.updateRight;
      this.searchInfoMation("no");
    },
    clearJumpId() {
      this.active = false;
      this.jumpId = null;
    },
    openDialog() {
      this.isCreate = false;
      this.dialogVisible1 = true;
    },
    changeActive(id) {
      this.active = true;
      this.jumpId = id;
    },
    getSize(res) {
      if (res < 1 * 1024 * 1024) {
        return `${(res / 1024).toFixed(2)}KB`;
      } else if (res < 1 * 1024 * 1024 * 1024) {
        return `${(res / 1024 / 1024).toFixed(2)}MB`;
      } else if (res < 1 * 1024 * 1024 * 1024 * 1024) {
        return `${(res / 1024 / 1024 / 1024).toFixed(2)}GB`;
      }
    }
  }
};
</script>
<style scoped lang='scss'>
.el-notification__content {
  p {
    width: 280px !important;
  }
}
</style>

